<?php defined('SYS_PATH') or die('No direct script access.');
/**
 * My Controller
 */
abstract class Controller extends TrueBlood_Controller
{
    /**
     * Display view
     *
     * @param string $tpl
     * @param array $vars
     */
    protected function view($tpl, $vars = array())
    {
        $this->response->disableBrowserCache();
        $this->response->charset(CHARSET, 'text/html');
        $data = array
        (
            'content' => $this->view->fetch($tpl, $vars)
        );
        $this->view->display('main', $data);
    }

    /**
     * Error output
     *
     * @param int $code
     * @param mixed $data
     * @return void
     */
    protected function error($code = 0, $data = null)
    {
        $output = array('code' => $code);
        if (null !== $data)
        {
            $output['data'] = $data;
        }
        $this->output($output);
    }

    /**
     * Succcess output
     *
     * @param mixed $data
     * @return void
     */
    protected function success($data = null)
    {
        $output = array('code' => 1);
        if (null !== $data)
        {
            $output['data'] = $data;
        }
        $this->output($output);
    }

    /**
     * Output
     *
     * @param mixed $data
     * @param string $format
     * @return void
     */
    protected function output($data, $format = 'json', $charset = 'UTF-8')
    {
        $output = strtolower($format) . 'Encode';
        echo $this->$output($data, $charset);
        exit();
    }

    /**
     * JSON encode
     *
     * @param mixed $data
     * @return string
     */
    protected function jsonEncode($data)
    {
        $output = '';
        $set_domain = $this->input('domain');
        if ('on' === $set_domain && $domain = $this->cofig->item('document_domain'))
        {
            $output .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" . CHARSET . "\" />\n";
            $output .= "<script type=\"text/javascript\">document.domain=\"{$domain}\";</script>\n";
        }
        $varname = $this->input('varname', null);
        if (null !== $varname && preg_match("/^([a-z0-9])+$/i", $varname))
        {
            $output = $output . $varname . '=';
        }
        $output .= json_encode($data);
        return $output;
    }
}

?>